package com.huiyujinrong.qiangdanbao.utils;

import android.Manifest;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

/**
 * 系统相关工具
 * Created by April on 2017/3/31.
 */

public class OSUtils {

    private OSUtils() {

    }

    /**
     * @param context 上下文
     * @return APP版本号（VersionName）
     */
    public static String getAPPVersion(@NonNull Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return "V" + packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "V1.0.0";
        }
    }

    /**
     * @param context      上下文（此处限定为 applicationContext）
     * @param metaDataName metaData 渠道 KEY
     * @return 打包渠道名
     */
    public static String getPackageChannelFromMetaData(
            @NonNull Application context,
            String metaDataName) {
        try {
            ApplicationInfo info = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            String channel = info.metaData.getString(metaDataName);
            return channel == null ? "" : channel;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "develop";
        }
    }

    /**
     * @param context 上下文
     * @return 手机 IMEI 号
     */
    public static String getPhoneIMEI(@NonNull Context context) {
        String model = Build.MANUFACTURER;
        if (model.equals("Xiaomi")) {
            return "866538023480207";//小米的
        } else {
            TelephonyManager manager = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String imei = manager.getDeviceId();
            if (imei == null) {
                imei = UUID.randomUUID().toString();
            }
            return imei;
        }
    }

    /**
     * @return 手机型号
     */
    public static String getPhoneModel() {
        return Build.MODEL;
    }

    /**
     * @return android系统版本号
     */
    public static String getAndroidVersion() {
        return Build.VERSION.RELEASE;
    }

    /**
     * @param context 上下文
     * @return 当前地理位置对应的城市名
     */
    public static String getCityName(@NonNull Context context) {
        LocationManager locationManager;
        String contextString = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) context.getSystemService(contextString);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(false);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        String cityName = null;
        // 取得效果最好的criteria
        String provider = locationManager.getBestProvider(criteria, true);
        if (provider == null) {
            return null;
        }
        // 得到坐标相关的信息
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return null;
        }
        Location location = locationManager.getLastKnownLocation(provider);
        if (location == null) {
            return null;
        }
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        // 更具地理环境来确定编码
        Geocoder gc = new Geocoder(context, Locale.getDefault());
        try {
            // 取得地址相关的一些信息经度、纬度
            List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
            StringBuilder sb = new StringBuilder();
            if (addresses.size() > 0) {
                Address address = addresses.get(0);
                sb.append(address.getLocality()).append(" ");
                cityName = sb.toString();
            }
        } catch (IOException e) {
            return null;
        }
        return cityName;
    }

}
